package com.example.sjc715.login

import androidx.lifecycle.viewModelScope
import com.example.commonlibrary.mvi.BaseViewModel
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class LoginViewModel:BaseViewModel<LoginIntent,LoginState>() {
    init {
        viewModelScope.launch {
            intent.consumeAsFlow().collect{
                when(it){
                    is LoginIntent.LoginI->getLogin(it.pwd,it.name)
                }
            }
        }
    }

    private suspend fun getLogin(pwd: String, name: String) {
        val s = try {
            val res = service.login(pwd, name)
            if(res.code == 0){
                LoginState.LoginSuccess(res)
            }else{
                LoginState.Failure(res.msg)
            }
        }catch (e:Exception){
            LoginState.Failure(e.message?:"")
        }
        state.postValue(s)
    }
}